package com.tiantian.quanminxiu.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.shenglian.utils.utils.CommonUtils;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tiantian.quanminxiu.api.AnchorService;
import com.tiantian.quanminxiu.api.QQService;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.ApplicationBase;
import com.tiantian.quanminxiu.utils.Constants;
import com.tiantian.quanminxiu.utils.UserData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by admin on 2016/9/28.
 */
public class Activity_QQLoginHelper extends Activity implements IUiListener {

    //region 初始化数据
    private Tencent tencent;
    private static QQLoginHelperBackCall qqLoginHelperBackCall;
    public String access_token = "";
    public String openid = "";
    public String expires_in;
    public String refresh_token = "";
    public int isLogin = 0;// 判断是登录还是分享 0登录 1分享好友 2分享空间
    private int roomId;
    private String anchorName;
    private String title;
    //endregion

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isLogin = getIntent().getIntExtra("isLogin", 0);
        roomId = getIntent().getIntExtra("roomId", 0);
        anchorName = getIntent().getStringExtra("anchorName");
        title = getIntent().getStringExtra("title");

        tencent = Tencent.createInstance(ApplicationBase.QQ_AppId, this);
        if(isLogin==0){
            if (!tencent.isSessionValid()) {
                tencent.login(this, "all", this);
            } else {
                CommonUtils.showToask(this,"QQ登录APPID等失效，注册失败");
                finish();
            }
        }else {
            if(roomId<=0){
                CommonUtils.showToask(this,"房间号错误");
                finish();
            }
            if(isLogin==1){
                ShareToQQ(anchorName,roomId,title);
            }else {
                shareToQzone(anchorName,roomId,title);
            }
        }
    }

    //region qq分享 ShareToQQ(String anchor,int roomId)
    public void ShareToQQ(String anchor,int roomId,String title) {

        Bundle bundle = new Bundle();
        // 这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, ApplicationBase.downAppUrl);
        // 分享的标题。注：PARAM_TITLE、PARAM_IMAGE_URL、PARAM_ SUMMARY不能全为空，最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, "全民秀做全民参与的直播平台~");
        // 分享的图片URL
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,APPUtils.createUserCover(roomId));
        // 分享的消息摘要，最长50个字
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY,"你的好友《"+anchor+"》正在全民秀直播["+title+"]");
        // 手Q客户端顶部，替换“返回”按钮文字，如果为空，用返回代替
        bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, "返回全民秀直播");
        tencent.shareToQQ(this, bundle, this);
    }
    //endregion

    //region 分享到空间 shareToQzone (String anchor,int roomId)
    private void shareToQzone (String anchor,int roomId,String title) {
        Bundle bundle = new Bundle();
        ArrayList<String> list = new ArrayList<>();
        list.add(APPUtils.createUserCover(roomId));
        bundle.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT );
        bundle.putString(QzoneShare.SHARE_TO_QQ_TITLE, "全民秀做全民参与的直播平台~");//必填
        bundle.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "你的好友《"+anchor+"》正在全民秀直播["+title+"]");//选填
        bundle.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,  ApplicationBase.downAppUrl);//必填
        bundle.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, list);
        tencent.shareToQzone(this, bundle, this);
    }
    //endregion


    static void setQQLoginHelperBackCall(QQLoginHelperBackCall backCall){
        qqLoginHelperBackCall = backCall;
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, this);
    }

    @Override
    public void onComplete(Object o) {
        if(isLogin==0){
            try {
                JSONObject obj = new JSONObject(o.toString());
                access_token = obj.optString("access_token");
                openid = obj.optString("openid");
                expires_in = obj.optString("expires_in");
                refresh_token = obj.optString("refresh_token");
                QQService.Factory.create().get_simple_userinfo(openid,access_token,ApplicationBase.QQ_AppId,"json")
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.newThread())
                        .subscribe(str -> {
                            try {
                                JSONObject object = new JSONObject(str.string());
                                String nickname = object.optString("nickname");
                                String gender = object.optString("gender");
                                String province = object.optString("province");
                                String city = object.optString("city");
                                String figureurl_1 = object.optString("figureurl_1");
                                String figureurl_2 = object.optString("figureurl_2");
                                String figureurl_qq_1 = object.optString("figureurl_qq_1");
                                String figureurl_qq_2 = object.optString("figureurl_qq_2");
                                if(qqLoginHelperBackCall!=null){
                                    qqLoginHelperBackCall.backcall(openid,access_token,expires_in,refresh_token,nickname,gender);
                                    finish();
                                }else {
                                    throw new RuntimeException("网络请求失败，请重试..");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        },throwable -> {
                            CommonUtils.showToask(this,"qq登录失败:"+throwable.getMessage());
                            finish();
                        });
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }else {
            CommonUtils.showToask(this,"分享成功");
            ApplicationBase app = ApplicationBase.get(this);
            AnchorService anchorService = app.getAnchorService();
            anchorService.share(UserData.Current.mid, Constants.APP_TYPE,UserData.Current.sign,0)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(app.defaultSubscribeScheduler())
                    .subscribe(str -> {
                        CommonUtils.showToask(this,str.optString("msg"));
                        UserData.Reload.Fragment_Mine = true;
                        UserData.Base.Coin += 5;
                        finish();
                    }, throwable -> {
                        finish();
                    });
        }
    }

    @Override
    public void onError(UiError uiError) {
        if(isLogin==0){
            CommonUtils.showToask(this,"登录失败："+uiError.errorMessage+":"+uiError.errorDetail);
            qqLoginHelperBackCall.onError("登录失败");
        }else {
            CommonUtils.showToask(this,"分享失败："+uiError.errorMessage+":"+uiError.errorDetail);
        }
        finish();
    }

    @Override
    public void onCancel() {
        if(isLogin==0){
            CommonUtils.showToask(this,"登录取消");
            qqLoginHelperBackCall.onError("登录取消");
        }else {
            CommonUtils.showToask(this,"分享取消");
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        qqLoginHelperBackCall = null;
    }

    public interface QQLoginHelperBackCall{
        void backcall(String Sopenid ,String access_token,String expires_in,String refresh_token,String nickname,String sex);
        void onError(String msg);
    }
}
